import { Modal } from "antd";
import { useState, useRef, useEffect } from "react";

// 将表单组件作为入参
const withForm = (FormCmp) => {
  const CmpWithForm = ({ visible, title, okText, okTrigger, cancelTrigger, afterClose }) => {
    const [isOpen, setIsOpen] = useState(visible);
    const formRef = useRef(null);
    const okHandler = () => {
      setIsOpen(false);
      // 获取表单数据
      const formData = formRef.current.getFormData();
      if (okTrigger) {
        // 将表单数据传给外部的处理函数
        okTrigger(formData);
      }
    }
    const cancelHandler = () => {
      setIsOpen(false);
      if (cancelTrigger) {
        cancelTrigger();
      }
    }

    useEffect(() => {
      if (!isOpen) {
        // 关闭后销毁dom
        afterClose(); 
      }
    }, [isOpen])

    return (
      <Modal
        title={title}
        open={isOpen}
        onOk={okHandler}
        onCancel={cancelHandler}
        okText={okText}
        maskClosable={false}
      >
        <div style={{ marginTop: '40px', marginRight: '40px' }}>
          <FormCmp ref={formRef} />
        </div>
      </Modal>
    )

  }

  return CmpWithForm;
}

export default withForm;